
%% bare_jrnl_compsoc.tex
%% V1.3
%% 2007/01/11
%% by Michael Shell
%% See:
%% http://www.michaelshell.org/
%% for current contact information.
%%
%% This is a skeleton file demonstrating the use of IEEEtran.cls
%% (requires IEEEtran.cls version 1.7 or later) with an IEEE Computer
%% Society journal paper.
%%
%% Support sites:
%% http://www.michaelshell.org/tex/ieeetran/
%% http://www.ctan.org/tex-archive/macros/latex/contrib/IEEEtran/
%% and
%% http://www.ieee.org/

%%*************************************************************************
%% Legal Notice:
%% This code is offered as-is without any warranty either expressed or
%% implied; without even the implied warranty of MERCHANTABILITY or
%% FITNESS FOR A PARTICULAR PURPOSE! 
%% User assumes all risk.
%% In no event shall IEEE or any contributor to this code be liable for
%% any damages or losses, including, but not limited to, incidental,
%% consequential, or any other damages, resulting from the use or misuse
%% of any information contained here.
%%
%% All comments are the opinions of their respective authors and are not
%% necessarily endorsed by the IEEE.
%%
%% This work is distributed under the LaTeX Project Public License (LPPL)
%% ( http://www.latex-project.org/ ) version 1.3, and may be freely used,
%% distributed and modified. A copy of the LPPL, version 1.3, is included
%% in the base LaTeX documentation of all distributions of LaTeX released
%% 2003/12/01 or later.
%% Retain all contribution notices and credits.
%% ** Modified files should be clearly indicated as such, including  **
%% ** renaming them and changing author support contact information. **
%%
%% File list of work: IEEEtran.cls, IEEEtran_HOWTO.pdf, bare_adv.tex,
%%                    bare_conf.tex, bare_jrnl.tex, bare_jrnl_compsoc.tex
%%*************************************************************************

% *** Authors should verify (and, if needed, correct) their LaTeX system  ***
% *** with the testflow diagnostic prior to trusting their LaTeX platform ***
% *** with production work. IEEE's font choices can trigger bugs that do  ***
% *** not appear when using other class files.                            ***
% The testflow support page is at:
% http://www.michaelshell.org/tex/testflow/




% Note that the a4paper option is mainly intended so that authors in
% countries using A4 can easily print to A4 and see how their papers will
% look in print - the typesetting of the document will not typically be
% affected with changes in paper size (but the bottom and side margins will).
% Use the testflow package mentioned above to verify correct handling of
% both paper sizes by the user's LaTeX system.
%
% Also note that the "draftcls" or "draftclsnofoot", not "draft", option
% should be used if it is desired that the figures are to be displayed in
% draft mode.
%
% The Computer Society usually requires 10pt for submissions.
%
\documentclass[10pt,journal,cspaper,compsoc]{IEEEtran}
%
% If IEEEtran.cls has not been installed into the LaTeX system files,
% manually specify the path to it like:
% \documentclass[12pt,journal,compsoc]{../sty/IEEEtran}





% Some very useful LaTeX packages include:
% (uncomment the ones you want to load)


% *** MISC UTILITY PACKAGES ***
%
%\usepackage{ifpdf}
% Heiko Oberdiek's ifpdf.sty is very useful if you need conditional
% compilation based on whether the output is pdf or dvi.
% usage:
% \ifpdf
%   % pdf code
% \else
%   % dvi code
% \fi
% The latest version of ifpdf.sty can be obtained from:
% http://www.ctan.org/tex-archive/macros/latex/contrib/oberdiek/
% Also, note that IEEEtran.cls V1.7 and later provides a builtin
% \ifCLASSINFOpdf conditional that works the same way.
% When switching from latex to pdflatex and vice-versa, the compiler may
% have to be run twice to clear warning/error messages.






% *** CITATION PACKAGES ***
%
\ifCLASSOPTIONcompsoc
  % IEEE Computer Society needs nocompress option
  % requires cite.sty v4.0 or later (November 2003)
  % \usepackage[nocompress]{cite}
\else
  % normal IEEE
  % \usepackage{cite}
\fi
% cite.sty was written by Donald Arseneau
% V1.6 and later of IEEEtran pre-defines the format of the cite.sty package
% \cite{} output to follow that of IEEE. Loading the cite package will
% result in citation numbers being automatically sorted and properly
% "compressed/ranged". e.g., [1], [9], [2], [7], [5], [6] without using
% cite.sty will become [1], [2], [5]--[7], [9] using cite.sty. cite.sty's
% \cite will automatically add leading space, if needed. Use cite.sty's
% noadjust option (cite.sty V3.8 and later) if you want to turn this off.
% cite.sty is already installed on most LaTeX systems. Be sure and use
% version 4.0 (2003-05-27) and later if using hyperref.sty. cite.sty does
% not currently provide for hyperlinked citations.
% The latest version can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/cite/
% The documentation is contained in the cite.sty file itself.
%
% Note that some packages require special options to format as the Computer
% Society requires. In particular, Computer Society  papers do not use
% compressed citation ranges as is done in typical IEEE papers
% (e.g., [1]-[4]). Instead, they list every citation separately in order
% (e.g., [1], [2], [3], [4]). To get the latter we need to load the cite
% package with the nocompress option which is supported by cite.sty v4.0
% and later. Note also the use of a CLASSOPTION conditional provided by
% IEEEtran.cls V1.7 and later.





% *** GRAPHICS RELATED PACKAGES ***
%
\ifCLASSINFOpdf
  % \usepackage[pdftex]{graphicx}
  % declare the path(s) where your graphic files are
  % \graphicspath{{../pdf/}{../jpeg/}}
  % and their extensions so you won't have to specify these with
  % every instance of \includegraphics
  % \DeclareGraphicsExtensions{.pdf,.jpeg,.png}
\else
  % or other class option (dvipsone, dvipdf, if not using dvips). graphicx
  % will default to the driver specified in the system graphics.cfg if no
  % driver is specified.
  % \usepackage[dvips]{graphicx}
  % declare the path(s) where your graphic files are
  % \graphicspath{{../eps/}}
  % and their extensions so you won't have to specify these with
  % every instance of \includegraphics
  % \DeclareGraphicsExtensions{.eps}
\fi
% graphicx was written by David Carlisle and Sebastian Rahtz. It is
% required if you want graphics, photos, etc. graphicx.sty is already
% installed on most LaTeX systems. The latest version and documentation can
% be obtained at: 
% http://www.ctan.org/tex-archive/macros/latex/required/graphics/
% Another good source of documentation is "Using Imported Graphics in
% LaTeX2e" by Keith Reckdahl which can be found as epslatex.ps or
% epslatex.pdf at: http://www.ctan.org/tex-archive/info/
%
% latex, and pdflatex in dvi mode, support graphics in encapsulated
% postscript (.eps) format. pdflatex in pdf mode supports graphics
% in .pdf, .jpeg, .png and .mps (metapost) formats. Users should ensure
% that all non-photo figures use a vector format (.eps, .pdf, .mps) and
% not a bitmapped formats (.jpeg, .png). IEEE frowns on bitmapped formats
% which can result in "jaggedy"/blurry rendering of lines and letters as
% well as large increases in file sizes.
%
% You can find documentation about the pdfTeX application at:
% http://www.tug.org/applications/pdftex





% *** MATH PACKAGES ***
%
%\usepackage[cmex10]{amsmath}
% A popular package from the American Mathematical Society that provides
% many useful and powerful commands for dealing with mathematics. If using
% it, be sure to load this package with the cmex10 option to ensure that
% only type 1 fonts will utilized at all point sizes. Without this option,
% it is possible that some math symbols, particularly those within
% footnotes, will be rendered in bitmap form which will result in a
% document that can not be IEEE Xplore compliant!
%
% Also, note that the amsmath package sets \interdisplaylinepenalty to 10000
% thus preventing page breaks from occurring within multiline equations. Use:
%\interdisplaylinepenalty=2500
% after loading amsmath to restore such page breaks as IEEEtran.cls normally
% does. amsmath.sty is already installed on most LaTeX systems. The latest
% version and documentation can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/required/amslatex/math/





% *** SPECIALIZED LIST PACKAGES ***
%
%\usepackage{algorithmic}
% algorithmic.sty was written by Peter Williams and Rogerio Brito.
% This package provides an algorithmic environment fo describing algorithms.
% You can use the algorithmic environment in-text or within a figure
% environment to provide for a floating algorithm. Do NOT use the algorithm
% floating environment provided by algorithm.sty (by the same authors) or
% algorithm2e.sty (by Christophe Fiorio) as IEEE does not use dedicated
% algorithm float types and packages that provide these will not provide
% correct IEEE style captions. The latest version and documentation of
% algorithmic.sty can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/algorithms/
% There is also a support site at:
% http://algorithms.berlios.de/index.html
% Also of interest may be the (relatively newer and more customizable)
% algorithmicx.sty package by Szasz Janos:
% http://www.ctan.org/tex-archive/macros/latex/contrib/algorithmicx/




% *** ALIGNMENT PACKAGES ***
%
%\usepackage{array}
% Frank Mittelbach's and David Carlisle's array.sty patches and improves
% the standard LaTeX2e array and tabular environments to provide better
% appearance and additional user controls. As the default LaTeX2e table
% generation code is lacking to the point of almost being broken with
% respect to the quality of the end results, all users are strongly
% advised to use an enhanced (at the very least that provided by array.sty)
% set of table tools. array.sty is already installed on most systems. The
% latest version and documentation can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/required/tools/


%\usepackage{mdwmath}
%\usepackage{mdwtab}
% Also highly recommended is Mark Wooding's extremely powerful MDW tools,
% especially mdwmath.sty and mdwtab.sty which are used to format equations
% and tables, respectively. The MDWtools set is already installed on most
% LaTeX systems. The lastest version and documentation is available at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/mdwtools/


% IEEEtran contains the IEEEeqnarray family of commands that can be used to
% generate multiline equations as well as matrices, tables, etc., of high
% quality.


%\usepackage{eqparbox}
% Also of notable interest is Scott Pakin's eqparbox package for creating
% (automatically sized) equal width boxes - aka "natural width parboxes".
% Available at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/eqparbox/





% *** SUBFIGURE PACKAGES ***
%\ifCLASSOPTIONcompsoc
%\usepackage[tight,normalsize,sf,SF]{subfigure}
%\else
%\usepackage[tight,footnotesize]{subfigure}
%\fi
% subfigure.sty was written by Steven Douglas Cochran. This package makes it
% easy to put subfigures in your figures. e.g., "Figure 1a and 1b". For IEEE
% work, it is a good idea to load it with the tight package option to reduce
% the amount of white space around the subfigures. Computer Society papers
% use a larger font and \sffamily font for their captions, hence the
% additional options needed under compsoc mode. subfigure.sty is already
% installed on most LaTeX systems. The latest version and documentation can
% be obtained at:
% http://www.ctan.org/tex-archive/obsolete/macros/latex/contrib/subfigure/
% subfigure.sty has been superceeded by subfig.sty.


%\ifCLASSOPTIONcompsoc
%  \usepackage[caption=false]{caption}
%  \usepackage[font=normalsize,labelfont=sf,textfont=sf]{subfig}
%\else
%  \usepackage[caption=false]{caption}
%  \usepackage[font=footnotesize]{subfig}
%\fi
% subfig.sty, also written by Steven Douglas Cochran, is the modern
% replacement for subfigure.sty. However, subfig.sty requires and
% automatically loads Axel Sommerfeldt's caption.sty which will override
% IEEEtran.cls handling of captions and this will result in nonIEEE style
% figure/table captions. To prevent this problem, be sure and preload
% caption.sty with its "caption=false" package option. This is will preserve
% IEEEtran.cls handing of captions. Version 1.3 (2005/06/28) and later 
% (recommended due to many improvements over 1.2) of subfig.sty supports
% the caption=false option directly:
%\ifCLASSOPTIONcompsoc
%  \usepackage[caption=false,font=normalsize,labelfont=sf,textfont=sf]{subfig}
%\else
%  \usepackage[caption=false,font=footnotesize]{subfig}
%\fi
%
% The latest version and documentation can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/subfig/
% The latest version and documentation of caption.sty can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/caption/




% *** FLOAT PACKAGES ***
%
%\usepackage{fixltx2e}
% fixltx2e, the successor to the earlier fix2col.sty, was written by
% Frank Mittelbach and David Carlisle. This package corrects a few problems
% in the LaTeX2e kernel, the most notable of which is that in current
% LaTeX2e releases, the ordering of single and double column floats is not
% guaranteed to be preserved. Thus, an unpatched LaTeX2e can allow a
% single column figure to be placed prior to an earlier double column
% figure. The latest version and documentation can be found at:
% http://www.ctan.org/tex-archive/macros/latex/base/



%\usepackage{stfloats}
% stfloats.sty was written by Sigitas Tolusis. This package gives LaTeX2e
% the ability to do double column floats at the bottom of the page as well
% as the top. (e.g., "\begin{figure*}[!b]" is not normally possible in
% LaTeX2e). It also provides a command:
%\fnbelowfloat
% to enable the placement of footnotes below bottom floats (the standard
% LaTeX2e kernel puts them above bottom floats). This is an invasive package
% which rewrites many portions of the LaTeX2e float routines. It may not work
% with other packages that modify the LaTeX2e float routines. The latest
% version and documentation can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/sttools/
% Documentation is contained in the stfloats.sty comments as well as in the
% presfull.pdf file. Do not use the stfloats baselinefloat ability as IEEE
% does not allow \baselineskip to stretch. Authors submitting work to the
% IEEE should note that IEEE rarely uses double column equations and
% that authors should try to avoid such use. Do not be tempted to use the
% cuted.sty or midfloat.sty packages (also by Sigitas Tolusis) as IEEE does
% not format its papers in such ways.




%\ifCLASSOPTIONcaptionsoff
%  \usepackage[nomarkers]{endfloat}
% \let\MYoriglatexcaption\caption
% \renewcommand{\caption}[2][\relax]{\MYoriglatexcaption[#2]{#2}}
%\fi
% endfloat.sty was written by James Darrell McCauley and Jeff Goldberg.
% This package may be useful when used in conjunction with IEEEtran.cls'
% captionsoff option. Some IEEE journals/societies require that submissions
% have lists of figures/tables at the end of the paper and that
% figures/tables without any captions are placed on a page by themselves at
% the end of the document. If needed, the draftcls IEEEtran class option or
% \CLASSINPUTbaselinestretch interface can be used to increase the line
% spacing as well. Be sure and use the nomarkers option of endfloat to
% prevent endfloat from "marking" where the figures would have been placed
% in the text. The two hack lines of code above are a slight modification of
% that suggested by in the endfloat docs (section 8.3.1) to ensure that
% the full captions always appear in the list of figures/tables - even if
% the user used the short optional argument of \caption[]{}.
% IEEE papers do not typically make use of \caption[]'s optional argument,
% so this should not be an issue. A similar trick can be used to disable
% captions of packages such as subfig.sty that lack options to turn off
% the subcaptions:
% For subfig.sty:
% \let\MYorigsubfloat\subfloat
% \renewcommand{\subfloat}[2][\relax]{\MYorigsubfloat[]{#2}}
% For subfigure.sty:
% \let\MYorigsubfigure\subfigure
% \renewcommand{\subfigure}[2][\relax]{\MYorigsubfigure[]{#2}}
% However, the above trick will not work if both optional arguments of
% the \subfloat/subfig command are used. Furthermore, there needs to be a
% description of each subfigure *somewhere* and endfloat does not add
% subfigure captions to its list of figures. Thus, the best approach is to
% avoid the use of subfigure captions (many IEEE journals avoid them anyway)
% and instead reference/explain all the subfigures within the main caption.
% The latest version of endfloat.sty and its documentation can obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/endfloat/
%
% The IEEEtran \ifCLASSOPTIONcaptionsoff conditional can also be used
% later in the document, say, to conditionally put the References on a 
% page by themselves.




% *** PDF, URL AND HYPERLINK PACKAGES ***
%
%\usepackage{url}
% url.sty was written by Donald Arseneau. It provides better support for
% handling and breaking URLs. url.sty is already installed on most LaTeX
% systems. The latest version can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/misc/
% Read the url.sty source comments for usage information. Basically,
% \url{my_url_here}.





% *** Do not adjust lengths that control margins, column widths, etc. ***
% *** Do not use packages that alter fonts (such as pslatex).         ***
% There should be no need to do such things with IEEEtran.cls V1.6 and later.
% (Unless specifically asked to do so by the journal or conference you plan
% to submit to, of course. )


% correct bad hyphenation here
\hyphenation{op-tical net-works semi-conduc-tor}
\usepackage[utf8]{inputenc}
\usepackage{listings}
\lstset{
language=Python,
showstringspaces=false,
tabsize=2}
\begin{document}
%
% paper title
% can use linebreaks \\ within to get better formatting as desired
\title{Aplicação de Segurança Informática}
%
%
% author names and IEEE memberships
% note positions of commas and nonbreaking spaces ( ~ ) LaTeX will not break
% a structure at a ~ so this keeps an author's name from being broken across
% two lines.
% use \thanks{} to gain access to the first footnote area
% a separate \thanks must be used for each paragraph as LaTeX2e's \thanks
% was not built to handle multiple paragraphs
%
%
%\IEEEcompsocitemizethanks is a special \thanks that produces the bulleted
% lists the Computer Society journals use for "first footnote" author
% affiliations. Use \IEEEcompsocthanksitem which works much like \item
% for each affiliation group. When not in compsoc mode,
% \IEEEcompsocitemizethanks becomes like \thanks and
% \IEEEcompsocthanksitem becomes a line break with idention. This
% facilitates dual compilation, although admittedly the differences in the
% desired content of \author between the different types of papers makes a
% one-size-fits-all approach a daunting prospect. For instance, compsoc 
% journal papers have the author affiliations above the "Manuscript
% received ..."  text while in non-compsoc journals this is reversed. Sigh.

\author{Pedro Moreira - 10015 e João Carlos Mendes, 12825}

% note the % following the last \IEEEmembership and also \thanks - 
% these prevent an unwanted space from occurring between the last author name
% and the end of the author line. i.e., if you had this:
% 
% \author{....lastname \thanks{...} \thanks{...} }
%                     ^------------^------------^----Do not want these spaces!
%
% a space would be appended to the last name and could cause every name on that
% line to be shifted left slightly. This is one of those "LaTeX things". For
% instance, "\textbf{A} \textbf{B}" will typeset as "A B" not "AB". To get
% "AB" then you have to do: "\textbf{A}\textbf{B}"
% \thanks is no different in this regard, so shield the last } of each \thanks
% that ends a line with a % and do not let a space in before the next \thanks.
% Spaces after \IEEEmembership other than the last one are OK (and needed) as
% you are supposed to have spaces between the names. For what it is worth,
% this is a minor point as most people would not even notice if the said evil
% space somehow managed to creep in.



% The paper headers
\markboth{ESTIG - IPBeja - MESI - Linguagens de Programação Dinâmicas, Março~2014}{}
%{Shell \MakeLowercase{\textit{et al.}}: Bare Demo of IEEEtran.cls for Computer Society Journals}
% The only time the second header will appear is for the odd numbered pages
% after the title page when using the twoside option.
% 
% *** Note that you probably will NOT want to include the author's ***
% *** name in the headers of peer review papers.                   ***
% You can use \ifCLASSOPTIONpeerreview for conditional compilation here if
% you desire.



% The publisher's ID mark at the bottom of the page is less important with
% Computer Society journal papers as those publications place the marks
% outside of the main text columns and, therefore, unlike regular IEEE
% journals, the available text space is not reduced by their presence.
% If you want to put a publisher's ID mark on the page you can do it like
% this:
%\IEEEpubid{0000--0000/00\$00.00~\copyright~2007 IEEE}
% or like this to get the Computer Society new two part style.
%\IEEEpubid{\makebox[\columnwidth]{\hfill 0000--0000/00/\$00.00~\copyright~2007 IEEE}%
%\hspace{\columnsep}\makebox[\columnwidth]{Published by the IEEE Computer Society\hfill}}
% Remember, if you use this you must call \IEEEpubidadjcol in the second
% column for its text to clear the IEEEpubid mark (Computer Society jorunal
% papers don't need this extra clearance.)




% for Computer Society papers, we must declare the abstract and index terms
% PRIOR to the title within the \IEEEcompsoctitleabstractindextext IEEEtran
% command as these need to go into the title area created by \maketitle.
\IEEEcompsoctitleabstractindextext{%
\begin{abstract}
%\boldmath
Este trabalho insere-se numa avaliação da disciplina Linguagens de Programação Dinâmicas, leccionada no âmbito do Mestrado em Engenharia de Segurança Informática no Instituto Politécnico de Beja. Pretende-se uma aplicação que permita verificar quais as portas abertas numa máquina na rede local, verificar quais as ligações estabelecidas localmente e efectuar o tratamento de ficheiros de log de firewall. A aplicação deve permitir exportar os dados em CSV e PDF. É possivel identificar o local geográfico da origem dos ips obtidos nas várias funcionalidades. 
\end{abstract}
% IEEEtran.cls defaults to using nonbold math in the Abstract.
% This preserves the distinction between vectors and scalars. However,
% if the journal you are submitting to favors bold math in the abstract,
% then you can use LaTeX's standard command \boldmath at the very start
% of the abstract to achieve this. Many IEEE journals frown on math
% in the abstract anyway. In particular, the Computer Society does
% not want either math or citations to appear in the abstract.

% Note that keywords are not normally used for peer review papers.
\begin{keywords}
Python, SQlite3, portscan, conscan, logscan, encription
\end{keywords}}


% make the title area
\maketitle

% To allow for easy dual compilation without having to reenter the
% abstract/keywords data, the \IEEEcompsoctitleabstractindextext text will
% not be used in maketitle, but will appear (i.e., to be "transported")
% here as \IEEEdisplaynotcompsoctitleabstractindextext when compsoc mode
% is not selected <OR> if conference mode is selected - because compsoc
% conference papers position the abstract like regular (non-compsoc)
% papers do!
\IEEEdisplaynotcompsoctitleabstractindextext
% \IEEEdisplaynotcompsoctitleabstractindextext has no effect when using
% compsoc under a non-conference mode.


% For peer review papers, you can put extra information on the cover
% page as needed:
% \ifCLASSOPTIONpeerreview
% \begin{center} \bfseries EDICS Category: 3-BBND \end{center}
% \fi
%
% For peerreview papers, this IEEEtran command inserts a page break and
% creates the second title. It will be ignored for other modes.
\IEEEpeerreviewmaketitle



\section{Introdução}
% Computer Society journal papers do something a tad strange with the very
% first section heading (almost always called "Introduction"). They place it
% ABOVE the main text! IEEEtran.cls currently does not do this for you.
% However, You can achieve this effect by making LaTeX jump through some
% hoops via something like:
%
%\ifCLASSOPTIONcompsoc
%  \noindent\raisebox{2\baselineskip}[0pt][0pt]%
%  {\parbox{\columnwidth}{\section{Introduction}\label{sec:introduction}%
%  \global\everypar=\everypar}}%
%  \vspace{-1\baselineskip}\vspace{-\parskip}\par
%\else
%  \section{Introduction}\label{sec:introduction}\par
%\fi
%
% Admittedly, this is a hack and may well be fragile, but seems to do the
% trick for me. Note the need to keep any \label that may be used right
% after \section in the above as the hack puts \section within a raised box.



% The very first letter is a 2 line initial drop letter followed
% by the rest of the first word in caps (small caps for compsoc).
% 
% form to use if the first word consists of a single letter:
% \IEEEPARstart{A}{demo} file is ....
% 
% form to use if you need the single drop letter followed by
% normal text (unknown if ever used by IEEE):
% \IEEEPARstart{A}{}demo file is ....
% 
% Some journals put the first two words in caps:
% \IEEEPARstart{T}{his demo} file is ....
% 
% Here we have the typical use of a "T" for an initial drop letter
% and "HIS" in caps to complete the first word.
\IEEEPARstart{O} trabalho efectuado abrange alguns pontos de verificação da rede informática com vista à identificação e detecção de vulnerabilidades na segurança da rede.\\
Desde logo a identificação de portos abertos nos dispositivos ligados na rede local permite actuar proactivamente na verificação da necessidade da existência de determinados serviços activos.\\
A análise dos logs produzidos pela firewall ufw poderá identificar possíveis intrusões e a visualização da localização geográfica da origem dos acessos externos pode dar a ideia da distribuição geográfica de potenciais ataques maliciosos, principalmente se os acessos forem persistentes.\\



\section{Estrutura de Ficheiros}
A aplicação elaborada é constituída por um conjunto de sete ficheiros:
\begin{itemize}
	\item scanner.py
	\item classes.py
	\item NmapScan.py
	\item LogScan.py
	\item ConScan.py
	\item Export.py
	\item GeoLiteCity.dat
\end{itemize}\\
A aplicação arranca quando é executado o programa $scanner.py$. No ficheiro classes.py residem as classes que através do $alchemy$\cite{alchemy} criam ou apenas fazem a ligação às tabelas na base de dados. Também se encontra aí a classe que efectua a ligação cifragem e decifragem da BD. Os ficheiros $NmapScan.py$, $LogScan.py$, $ConScan.py$ e $Export.py$ contêm classes com o mesmo nome, através dos quais se podem executar as operações da aplicação.\\
Para que a geoferenciação dos endereços ip funcione é necessária a utilização do ficheiro $GeoLiteCity.py$


\section{Autenticação e confidencialidade}
Não existe nenhum impedimento para qualquer utilizador do programa, no entanto os dados gerados por cada um apenas a ele pertencem e só podem ser acedidos através da disponibilização do username e password.\\
Sempre que o programa é executado, é necessário indicar o nome de utilizador. Posteriomente o sistema solicita a respectiva password através do módulo getpass \cite{getpass} que possibilita a inserção da mesma sem que esta seja apresentada no ecran.\\
São gerados os hash $md5$ do username e da password que após de aplicada a operação $XOR$: entre eles dá origem ao nome da base de dados para o utilizador com a password actuais.\\
Quando o programa termina, este cifra a base de dados com $AES-CBC-256$, utilizando como chave o hash $md5$ da password completada com o byte \textbackslash$0$\footnote{Este aspecto precisa ser melhorado} até ter a dimensão da chave necessária, neste caso usamos 256 bytes.\\
Ao iniciar o programa pode ter dois comportamentos. Ou cria uma nova base de dados no caso desta não existir, ou decifra a correspondente ao login efectuado.
\colchunk{\begin{lstlisting}[caption=Gerar o nome da base de dados, único para cada login,language=Python, label=login]{login}
u = hashlib.md5()
u.update(username)
self.username = u.hexdigest()
p = hashlib.md5()
p.update(password)
self.password = p.hexdigest()
db = ''.join(chr(ord(a) ^ ord(b))
	for a,b in zip(self.username, 
	self.password))
m = hashlib.md5()
m.update(db)
self.hash = m.hexdigest()
self.db_name = '%s.db' % self.hash
\end{lstlisting}}
        
\colchunk{\begin{lstlisting}[caption=Cifragem da base de dados,language=Python, label=cifra]{cifra}
def encrypt(self, message, key, key_size=256):
	message = self.pad(message)
	iv = Random.new().read(AES.block_size)
	cipher = AES.new(key, AES.MODE_CBC, iv)
	return iv + cipher.encrypt(message)

def pad(self, s):
	return s + b"\0" * 
		(AES.block_size - len(s) 
			% AES.block_size)
\end{lstlisting}}

\section{Base de dados}
O sistema de gestão de base de dados utilizado é a biblioteca SQLite3 \cite{SQLite3}. A ligação entre este e o Python é feito através do toolkit $Alchemy$.\\
Foram criadas classes que herdam uma $declarative base$ \cite{declarative_base}. Desta forma as classes ficam directamente mapeadas às tabelas correspondentes na base de dados.\\
As classes criadas foram:
\begin{itemize}
	\item IP(id, ip, country, country\_name, lon, lat)
	\item LogScanDB(id, time, fk ipsrc\_id)
	\item ConScanDB(id, local\_port, remote\_port, time, fk remote\_id\_id)
	\item NmapScanDB(id, port, time, protocol, fk ip\_id)
\end{itemize}
Através do toolkit $Alchemy$ é possível a inserção de registos na base de dados apenas criando um objecto da classe pretendida. Para tal é necessário criar uma sessão ligada à base de dados do login actual. Após a criação dos objectos necessários para a inserção dos registos na base de dados, estes podem ser guardados efectuando commit.\\
\colchunk{\begin{lstlisting}[caption=Exemplo de inserção de registos em sqlalchemy,language=Python, label=alchemy]{alchemy}
engine = create_engine('sqlite:///%s' 
	% self.db_name)
self.base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
self.session = DBSession()
one_ip = IP(ip='127.0.0.1', 
	country='PT', 
	country_name='Portugal', 
	lat=None, lon=None)
another_ip = IP('192.168.0.1', 'PT', 
	'Portugal', None, None)
self.session.add(one_ip)
self.session.add(another_ip)
self.session.commit()
\end{lstlisting}}

\section{Portscan}
Para verificar se uma ou mais portas estão abertas numa máquina a aplicação utiliza a biblioteca para python $python-nmap$\cite{nmap}. Esta biblioteca permite facilmente manipular resultados do conhecido nmap\cite{_nmap} e é uma boa ferramenta para administradores de sistemas, dando a possibilidade de serem criadas tarefas e relatórios automatizados.\\
A cada endereço de ip indicado no scan é também feita uma tentativa de geolocalização do mesmo com auxílio do \textit{GeoIP City Database} \cite{geoip}. Neste trabalho apenas é aproveitado o código do país, nome do país, latitude e longitude.\\
Cada IP envolvido é gravado ou associado a um registo na base de dados e cada porta encontrada aberta é também guardada sendo associada ao respectivo endereço de ip.\\
Na Listing \ref{pscan} é apresentado o código principal desta funcionalidade, sendo omitidas as impressões feitas ao longo da sua execução.\\
\colchunk{\begin{lstlisting}[caption=PortScan,language=Python, label=pscan]{pscan}
nm = nmap.PortScanner()
	nm.scan(self.ip, self.port)
	now = datetime.now()
	for host in nm.all_hosts():
		try:
			gi = GeoIP.open('GeoLiteCity.dat', 
				GeoIP.GEOIP_STANDARD)
			geo = gi.record_by_addr(host)
			country_=geo['country_code']
			country_name_=geo['country_name']
			lon_=geo['longitude']
			lat_=geo['latitude']
		except:
			country_ = None
			country_name_ = None
			lon_ = None
			lat_ = None
		finally:
			new_ip = IP(ip=host,
			country=country_,
			country_name=country_name_,
			lon=lon_,
			lat=lat_)
		ip_address = self.session.query(
			IP).filter_by(	ip=host).first()

		if ip_address == None:
			self.session.add(new_ip)
			ip_address = new_ip

		for proto in nm[host].all_protocols():
			if proto in ['tcp', 'udp']:
			lport = nm[host][proto].keys()
			lport.sort()
			for p in lport:
				nmp = NmapScanDB(port=p,
				time=now,
				protocol=proto,
				ip=ip_address)
	self.session.add(nmp)
	self.session.commit()
\end{lstlisting}}

\colchunk{\begin{lstlisting}[caption=Georeferenciação de um IP,language=Python, label=geoip]{geoip}
gi = GeoIP.open('GeoLiteCity.dat', 
	GeoIP.GEOIP_STANDARD)
geo = gi.record_by_addr(address)
country_ = geo['country_code']
country_name_ = geo['country_name']
lon_ = geo['longitude']
lat_ = geo['latitude']
new_ip = IP(ip=address, country=country_, 
	country_name=country_name_, 
	lon=lon_, lat=lat_)
\end{lstlisting}}

\section{Conscan}
Esta função do programa centra a sua utilização nas bibliotecas $psutil$ \cite{psutil} e $socket$ \cite{socket}. A aplicação começa por obter os processos que estão a ser executados localmente, filtrando-os por conexões do tipo $inet$. De seguida tenta obter a georeferencia do ip encontrado e armazena na base de dados as informações do ip, bem como porta local e remota, hora da ligação, o status da mesma, e qual o nome e id do processo responsável pela conexão.\\
A execução desta funcionalidade apenas é conseguida caso o utilizador tenha permissões de root.
\colchunk{\begin{lstlisting}[caption=Verificação de conexões locais,language=Python, label=conscan]{conscan}
AF_INET6 = getattr(socket, 'AF_INET6', 
	object())
proto_map = {(AF_INET, SOCK_STREAM)  : 'TCP',
	(AF_INET6, SOCK_STREAM) : 'TCP6',
	(AF_INET, SOCK_DGRAM)   : 'UDP',
	(AF_INET6, SOCK_DGRAM)  : 'UDP6'}
for p in psutil.process_iter():
	try:
		program = p.name
		con = p.get_connections(kind='inet')
 		for c in con:
           		if c.raddr:
				# obter a georeferenciacao
				new_ip = IP(
					ip=c.raddr[0], 
					country=country_, 
					country_name=country_name_, 
					lon=lon_, lat=lat_)
				ip = self.session.query(
					IP).filter_by(
					ip=c.raddr[0]).first()
				if ip == None:
					self.session.add(new_ip)
					ip = new_ip
				con = ConScanDB(
					local_port=c.laddr[1], 
					remote_port=c.raddr[1],
					time=datetime.now(), 
					remote_ip=ip)
				self.session.add(con)
	except:
		pass
self.session.commit()
\end{lstlisting}}

\section{Log scan}
Outra das funcionalidades da ferramenta é a capacidade de armazenar na base de dados os eventos registados no log de firewall, neste caso está apenas preparada para logs da firewall ufw \cite{ufw}
O programa percorre todas as linhas do log tentando, como noutros casos, obter a georeferenciação do ip, e armazena os dados.
\colchunk{\begin{lstlisting}[caption=Armazenamento de eventos de log,language=Python, label=logscan]{logscan}
for line in logfile.readlines():
	if not re.search("SRC=192", line) 
		and not re.search("SRC=0", line) 
		and not re.search("SRC=172", line):
	lista = line.split("SRC=")
	ip_src = lista[1].split(' ')[0]
	lineMonth = str(line)
	dataT = lineMonth[:15]
	device = line.split("IN=")
	dInterface = device[1].split(' ')[0]
	if (str(dInterface) ==""):
		device = line.split("OUT=")
		dInterface = device[1].split(' ')[0]
		event = line.split("IN= ")
		eventSrc = event[1].split('=')[0]
	else:
		eventSrc = "IN"
		proto=line.split("PROTO=")
		protoInf=proto[1].split(' ')[0]
	try:
		if len(ip_src)<=15:
			spt=line.split("SPT=")
			sptPort=spt[1].split(' ')[0]
			dpt=line.split("DPT=")
			dptPort=dpt[1].split(' ')[0]
			ttlinf=line.split("TTL=")
			ttlData=str(ttlinf[1].split(' ')[0])
		else:
			continue
		# ... verificar geoip e se ip existe ...
		log = LogScanDB(
			time = datetime.strptime(
				dataT, 
				"%b %d %H:%M:%S"),
			ipsrc = ip_address,
			event_src = eventSrc,
			device = dInterface,
			protocol = protoInf,
			ttl = ttlData,
			src_port = sptPort,
			dst_port = dptPort)
		self.session.add(log)
	except Exception as e:
           	print e
\end{lstlisting}}

\section{Exportar dados}
É possível exportar o conteúdo da base de dados para análise. Visto que a base de dados se encontra cifrada, podendo existir a necessidade de a obter na integra foi adicionada a possibilidade de se obter uma cópia da mesma já decifrada. O método utilizado é semelhante ao da cifra já explicado anteriormente.\\
Além de poder exportar toda a base de dados também há a possibilidade de exportar os dados em CSV ou PDF.
\subsection{CSV}
O ficheiro CSV é gerado com base no módulo de python $CSV$ \cite{csv}. O programa faz a pesquisa na base de dados por todos os registos e adiciona os resultados, agrupados por tipo. A listagem \ref{ecsv} mostra um exemplo do query à base de dados com o alchemy que também é usado para o tipo PDF.
\colchunk{\begin{lstlisting}[caption=Exportar CSV,language=Python, label=ecsv]{ecsv}
s = csv.writer(
	open(filename, 'wb'), 
 	delimiter=';',
	quotechar='\x22', 
	quoting=csv.QUOTE_MINIMAL)
#Query à base de dados com alchemy
conscans = 
	self.session.query(ConScanDB).all()
s.writerow(["LOCAL CONNECTIONS"])
s.writerow(["[Time]"]
	+ ["[Local Port]"]
	+ ["[Remote IP]"]
	+ ["[Remote Port]"])
 for line in conscans:
	s.writerow([line.time]
		+ [line.local_port]
           	+ [line.remote_ip.ip]
		+ [line.remote_port])
\end{lstlisting}}

\subsection{PDF}
A criação dos pdfs utiliza a biblioteca Reportlab \cite{rlab}. O documento é criado com tabelas que alojam os dados armazenados. Os endereços de IP apresentados podem ser clicados pois têm um link para o google maps centrado a sua geo localização.

\colchunk{\begin{lstlisting}[caption=Exportar PDF,language=Python, label=epdf]{epdf}
doc = SimpleDocTemplate(filename, 
	pagesize=landscape(A4))
elements = []
styles=getSampleStyleSheet()
styleN = styles["Normal"]
# Leitura de todos os conscans
scans =
	self.session.query(ConScanDB).all()
data = [["LOCAL CONNECTIONS"]]
elements.append(self.drawTable(data, 1))
data = [["Time","Local Port", 
	"Remote IP", "Remote Port"]]
for line in scans:
	data.append([line.time,
	line.local_port,
	Paragraph("<a href='
		https://maps.google.com/
		maps?q=loc:%s,%s'>%s</a>" 
		% (line.ipsrc.lat, line.ipsrc.lon, 
		line.ipsrc.ip),
	styles["Normal"]),
	line.remote_port])
elements.append(self.drawTable(data))
#  ....
doc.build(elements)
print "File saved to %s" % filename

def drawTable(self, data, blank = 0):
	result = Table(data,  repeatRows=1)
	result.hAlign = 'LEFT'
	if blank == 1:
		tblStyle = TableStyle(
			[('TEXTCOLOR',
				(0,0), (-1,-1),
				colors.black),
				('VALIGN',(0,0),
				(-1,-1),'TOP')])
	else:
		tblStyle = TableStyle([
			('TEXTCOLOR',(0,0),
				(-1,-1),colors.black),
			('VALIGN',(0,0),
				(-1,-1),'TOP'),
			('LINEBELOW',(0,0),
				(-1,-1),1,colors.black),
			('INNERGRID',(0,0),
				(-1,-1),1,colors.black),
				('BOX',(0,0),(-1,-1),
				1,colors.black)])
		tblStyle.add('BACKGROUND',(0,0),
			(-1,-1),colors.lightblue)
		tblStyle.add('BACKGROUND',(0,1),
			(-1,-1),colors.white)
	result.setStyle(tblStyle)
	return result
\end{lstlisting}}

\section{Utilização}
A utilização do programa basea-se em linha de comandos através da passagem de alguns argumentos. O tratamento desses argumentos é feito com auxílio do módulo de python Argparse \cite{argparse}.
\colchunk{\begin{lstlisting}[caption=Tratamento dos argumentos linha de comandos,language=Python, label=parse]{parse}
parser = argparse.ArgumentParser()
parser.add_argument("-u", "--username",
	required=True)
parser.add_argument("-portscan", 
	nargs=2, 
	metavar=('ip', 'ports'),
	required=False,
           help="Perform a portscan")
parser.add_argument("-conscan", 
	action='store_true',
	required=False,
	help="Scan for local connections")
parser.add_argument("-logscan", 
	nargs=1,
	metavar=('file'),
	required=False,
	help="Store log cons into database")
parser.add_argument("-export", 
	nargs=2,
	metavar=('filename', 'filetype'),
	required=False,
	help="export database [db, csv, pdf]")
parser.add_argument("-delete", 
	action="store_true",
	required=False,
	help="Delete database")
args = parser.parse_args()
\end{lstlisting}}
O programa é executado através do ficheiro$./scanner.py -u <username>$ e os argumentos disponíveis para a execução do programa são os apresentados abaixo, em todos eles é solicitada a password para a execução:
\begin{itemize}
\item $-conscan$\\
Verificação de conexões estabelecidas na máquina local
\item $-portscan <ip> <ports>$\\
Efectuar um portscan a uma máquina
\item $-logscan <log file>$\\
Tratamento dos dados de um ficheiro de log de firewall
\item $-export <filename> <filetype>$\\
Exportar os dados
\item $-delete$\\
Eliminar (limpar) a base de dados do utilizador activo
\end{itemize}

\section{Conclusão}
O trabalho foi realizado totalmente na linguagem de programação Python, utilizando-se bibliotecas standard e outras que pela sua natureza se mostraram muito eficazes neste projecto. As principais bibliotecas utilizadas foram a python-nmap que fornece um interface com o programa nmap, a python-psutil que disponibiliza funções sobre os processos.\\
Optamos por registar numa base de dados SQLite3 todas as informações recolhidas numa fase de inventariação de dados e posteriormente a disponibilização da informação registada para vários tipos de saída, tais como seja em formato db (SQLite), PDF ou CSV. Para maior segurança a base de dados é cifrada a partir dos dados do utilizador e respectiva senha para evitar acessos directos aos dados e assim existir maior segurança. Para interface com a base de dados optamos por utilizar a biblioteca python-sqlalchemy que permite interagir de forma simples com a maioria das base de dados entre as quais a SQLite utilizada neste projecto.\\
Para a disponibilização da informação em formato PDF utilizou-se a biblioteca python-reportlab a qual permite a criação de relatórios em formato PDF com muitas funcionalidades e potencialidades interessantes.
Também foi utilizado a biblioteca python-geoip que permite a localização geográfica de um IP público. A forma prática de como se fez a utilização desta biblioteca foi através das referências da latitude e longitude obtidas para cada IP, ser incluída num hyperlink em cada IP listado no formato PDF, para permitir ao utilizador aceder à localização geográfica via Google Maps.\\
Como melhoria ao projecto salientamos a possibilidade de através da biblioteca python-reportlabs serem criados gráficos e tabelas com dados estatísticos nos relatórios em formato PDF.


% (used to reserve space for the reference number labels box)
\begin{thebibliography}{30}

\bibitem{alchemy}
Michael Bayer. SQLAlchemy. Disponível no link \href{http://www.sqlalchemy.org}. Consultado em Março de 2014


\bibitem{SQLite3}
%This is an example of a book reference
SQLite, Disponível  no link \href{https://www.sqlite.org}. Consultado em Março de 2014 

\bibitem{getpass}
%This is an example of a book reference
Python. getpass — Portable password input. Disponível no link: \href{http://docs.python.org/2/library/getpass.html}. Consultado em Março de 2014

\bibitem{declarative_base}
%This is an example of a book reference
Declarative. SQLAlchemy 0.9 Documentation. Disponível no link: \href{http://docs.sqlalchemy.org/en/rel\_0\_9/orm/extensions/
declarative.html}. Consultado em Março de 2014

\bibitem{nmap}
%This is an example of a book reference
Python. python-nmap 0.3.3. Disponível no link: \href{https://pypi.python.org/pypi/python-nmap/0.3.3}. Consultado em Março de 2014

\bibitem{nmap_}
Nmap - Free Security Scanner For Network Exploration \& Security Audits. Disponível no link: \href{http://nmap.org/}. Consultado em Março de 2014

\bibitem{geoip}
Maxmind Developer Site. GeoIP City Database. Disponível no link: \href{http://dev.maxmind.com/geoip/legacy/install/city/}. Consultado em Março de 2014

\bibitem{psutil}
Python. psutil 2.0.0. Disponível no link: \href{https://pypi.python.org/pypi/psutil/}. Consultado em Março de 2014

\bibitem{socket}
Python. socket — Low-level networking interface. Disponível no link: \href{http://docs.python.org/2/library/socket.html}. Consultado em Março de 2014

\bibitem{ufw}
Ubuntu. UFW - Uncomplicated Firewall. Disponível no link: \href{https://help.ubuntu.com/community/UFW}. Consultado em Março de 2014

\bibitem{csv}
Python. csv — CSV File Reading and Writing. Disponível no link: \href{http://docs.python.org/2/library/csv.html}. Consultado em Março de 2014

\bibitem{rlab}
ReportLab: Open Source Python Libraries for PDF creation. Disponível no link: \href{http://www.reportlab.com/software/opensource/}. Consultado em Março de 2014

\bibitem{argparse}
Python. argparse — Parser for command-line options, arguments and sub-commands. Disponível no link: \href{http://docs.python.org/3.4/library/argparse.html}. Consultado em Março de 2014
%This is an example of a Transactions article reference
%D.S. Coming and O.G. Staadt, "Velocity-Aligned Discrete Oriented Polytopes for Dynamic Collision Detection," IEEE Trans. Visualization and Computer Graphics, vol.�14,� no.�1,� pp. 1-12,� Jan/Feb� 2008, doi:10.1109/TVCG.2007.70405.

%This is an example of a article from a conference proceeding
%H. Goto, Y. Hasegawa, and M. Tanaka, "Efficient Scheduling Focusing on the Duality of MPL Representation," Proc. IEEE Symp. Computational Intelligence in Scheduling (SCIS '07), pp. 57-64, Apr. 2007, doi:10.1109/SCIS.2007.367670.

%This is an example of a PrePrint reference
%J.M.P. Martinez, R.B. Llavori, M.J.A. Cabo, and T.B. Pedersen, "Integrating Data Warehouses with Web Data: A Survey," IEEE Trans. Knowledge and Data Eng., preprint, 21 Dec. 2007, doi:10.1109/TKDE.2007.190746.

%Again, see the IEEEtrans_HOWTO.pdf for several more bibliographical examples. Also, more style examples
%can be seen at http://www.computer.org/author/style/transref.htm
\end{thebibliography}

% biography section
% 
% If you have an EPS/PDF photo (graphicx package needed) extra braces are
% needed around the contents of the optional argument to biography to prevent
% the LaTeX parser from getting confused when it sees the complicated
% \includegraphics command within an optional argument. (You could create
% your own custom macro containing the \includegraphics command to make things
% simpler here.)
%\begin{biography}[{\includegraphics[width=1in,height=1.25in,clip,keepaspectratio]{mshell}}]{Michael Shell}
% or if you just want to reserve a space for a photo:


% You can push biographies down or up by placing
% a \vfill before or after them. The appropriate
% use of \vfill depends on what kind of text is
% on the last page and whether or not the columns
% are being equalized.

%\vfill

% Can be used to pull up biographies so that the bottom of the last one
% is flush with the other column.
%\enlargethispage{-5in}



% that's all folks
\end{document}



